package com.tchhy.mvplibrary.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.ActivityInfo
import android.net.ConnectivityManager
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.*
import android.view.inputmethod.InputMethodManager
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.annotation.ColorRes
import androidx.appcompat.widget.Toolbar
import com.google.android.material.appbar.AppBarLayout
import com.gyf.immersionbar.ImmersionBar
import com.tchhy.mvplibrary.ui.activity.PermissionActivity
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.api.RefreshHeader
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener
import com.tchhy.basemodule.NetworkStateReceiver
import com.tchhy.basemodule.StatusBarUtil
import com.tchhy.basemodule.common.ActivityManager
import com.tchhy.basemodule.common.Constants
import com.tchhy.basemodule.ext.dip2px
import com.tchhy.basemodule.widgets.dialog.ProgressLoadingDialog
import com.tchhy.mvplibrary.R
import com.tchhy.provider.URLConstant
import com.tchhy.provider.constant.UmengEvent
import com.trello.rxlifecycle2.LifecycleTransformer
import com.umeng.analytics.MobclickAgent
import java.io.Serializable

/**
 *基础Activity
 *
 * Author: wfy
 *
 * time: 2018/8/22
 *
 */
abstract class BaseActivity : PermissionActivity() {

    protected val imm: InputMethodManager? by lazy { getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager }

    //用于延迟弹出软键盘
    private val mHandler by lazy { Handler() }

    open lateinit var mLayoutInflater: LayoutInflater

    lateinit var mLoadingView: View
    lateinit var mErrorView: View
    lateinit var mEmptyView: View
    private var ivBack: View? = null

    protected var mProgressLoadingDialog: ProgressLoadingDialog? = null
    private lateinit var bindToLifecycle: LifecycleTransformer<*>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ActivityManager.addActivity(this)
        overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out)
        bindToLifecycle = bindToLifecycle<Any>()
        mLayoutInflater = LayoutInflater.from(this)
        //注册生命周期
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT//禁止横屏
        setContentView(setContentLayoutId())
//        CustomDesit.setCustomDensity(this, BaseApplication.app)//极简屏幕适配
        //沉浸式代码配置
        //当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
        StatusBarUtil.setRootViewFitsSystemWindows(this, keepStatusBarHeight())
        //设置状态栏透明
        StatusBarUtil.setTranslucentStatus(this)
        //一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
        //所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
        if (!StatusBarUtil.setStatusBarDarkTheme(this, isDarkTheme())) {
            //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
            //这样半透明+白=灰, 状态栏的文字能看得清
            StatusBarUtil.setStatusBarColor(this, 0x55000000)
        }

        //加载对话框
        mProgressLoadingDialog = ProgressLoadingDialog.create(this)
        findViewById<View>(R.id.iv_back)?.setOnClickListener {
            finish()
            overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out)
        }
        ivBack = findViewById(R.id.iv_back)
        ivBack?.let {
            it.setOnTouchListener { v, event ->
                if (event.action == MotionEvent.ACTION_DOWN) {
                    Log.i("BaseActivity", "MotionEvent.ACTION_DOWN")
                    val map = HashMap<String, String>()
                    map.put("name", localClassName)
                    MobclickAgent.onEvent(this, UmengEvent.navigation_Back, map)
                }
                return@setOnTouchListener false
            }
        }


    }

    open fun keepStatusBarHeight():Boolean{
        return true
    }

    abstract fun setContentLayoutId(): Int

    @ColorRes
    open fun navigationBarColor(immersionBar: ImmersionBar): Int {
        if (!isAutoNavigationBarDarkModeEnable()) {
            //导航栏图标是深色，不写默认为亮色
            immersionBar.navigationBarDarkIcon(true)
        } else {
            immersionBar.autoNavigationBarDarkModeEnable(true, 0.5f)
        }
        return R.color.common_white
    }


    //自动导航栏图标变色，必须指定导航栏颜色才可以自动变色哦
    open fun isAutoNavigationBarDarkModeEnable() = false

    open fun isDarkTheme() = true

    /**
     * 有导航栏的情况下，Activity是否全屏显示
     */
    open fun isFullScreen() = false

    override fun finish() {
        super.finish()
        hideSoftInput()
    }

    override fun onDestroy() {
        super.onDestroy()
        ActivityManager.removeActivity(this)
        mHandler.removeCallbacksAndMessages(mHandler)
        //解决InputMethodManager造成的内存泄露
        //  InputMethodManager::class.java.getDeclaredMethod("windowDismissed", IBinder::class.java).invoke(imm, window.decorView.windowToken)
      //  SystemUtils.fixInputMethodManagerLeak(this)
        mProgressLoadingDialog?.destroy()
        mHandler.removeCallbacksAndMessages(null)
    }


    fun showSoftInput() {
        mHandler.postDelayed({
            val currentFocusView = currentFocus
            if (currentFocusView != null && imm != null) {
                imm?.showSoftInput(currentFocusView, 0)
            }
        }, 100)
    }

    protected fun toggleSoftInput() {
        val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
        inputMethodManager?.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
    }

    fun hideSoftInput() {
        val localView = currentFocus
        if (localView != null && this.imm != null) {
            imm?.hideSoftInputFromWindow(localView.windowToken, 2)
        }
    }

    fun initToolbar(toolbar: Toolbar) {
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayShowTitleEnabled(false)
        toolbar.setNavigationOnClickListener{
            onBackPressed()
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        // Fragment 逐个出栈
        val count = supportFragmentManager.backStackEntryCount
        if (count == 0) {
            //super.onBackPressed()
            finish()
        } else {
            supportFragmentManager.popBackStack()
        }
    }


    /**
     * 初始化弹性头布局个人中心与歌手中心
     */
    protected fun initElasticHead(
        rlHeadContainer: RelativeLayout,
        smartRefreshLayout: SmartRefreshLayout,
        mAppBarLayout: AppBarLayout,
        ivCover: View,
        llExtraOperate: ViewGroup
    ) {
        val layoutParams = rlHeadContainer.layoutParams
        val headPx = rlHeadContainer.dip2px(this, URLConstant.DEFAUT_HEAD_APPBAR_HEIGHT)
        val coverPx = rlHeadContainer.dip2px(this, URLConstant.DEFAULT_COVER_HEIGHT)

        smartRefreshLayout.setOnMultiPurposeListener(object : SimpleMultiPurposeListener() {

            override fun onHeaderMoving(
                header: RefreshHeader?,
                isDragging: Boolean,
                percent: Float,
                offset: Int,
                headerHeight: Int,
                maxDragHeight: Int
            ) {
                if (offset > 0) {
                    val rate = offset.toFloat() / headPx.toFloat()
                    layoutParams.height = (headPx * (1f + rate)).toInt()
                    rlHeadContainer.layoutParams = layoutParams
                }
            }


/*            override fun onHeaderPulling(header: RefreshHeader?,
                                         percent: Float,
                                         offset: Int,
                                         headerHeight: Int,
                                         extendHeight: Int) {

            }


            override fun onHeaderReleasing(header: RefreshHeader?,
                                           percent: Float,
                                           offset: Int,
                                           footerHeight: Int,
                                           extendHeight: Int) {
                if (offset > 0) {
                    val rate = offset.toFloat() / headPx.toFloat()
                    layoutParams.height = (headPx * (1f + rate)).toInt()
                    rlHeadContainer.layoutParams = layoutParams
                }
            }*/
        })

        /*mAppBarLayout.addOnOffsetChangedListener { appBarLayout, verticalOffset ->
            if (verticalOffset <= 0) {
                layoutParams.height = headPx + verticalOffset
                rlHeadContainer.layoutParams = layoutParams
                val alpha = -verticalOffset.toFloat() / coverPx.toFloat()
                ivCover.alpha = alpha
                llExtraOperate.alpha = 1 - alpha
            }
        }*/
    }

    fun startAc(clazz: Class<*>, data: Serializable = "") {
        val intent = Intent(this, clazz)
        intent.putExtra(Constants.DATA, data)
        startActivity(intent)
    }


    open fun jumpToMainActivity() {
        try {
            var clz = Class.forName("com.tchhy.tcjk.ui.main.activity.MainActivity")
            startActivity(Intent(this, clz))
            finish()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }





    override fun setTitle(title : Int){
        title ?: return
        findViewById<TextView>(R.id.header_title)?.setText(title)
    }

    fun setTitleText(title : String){
        title ?: return
        findViewById<TextView>(R.id.header_title)?.setText(title)
    }

    fun setRightTitleClick(rightTitle: Int?, clickListener:View.OnClickListener) {
        setRightTitleClick(rightTitle, clickListener,null)
    }

    fun setRightTitleClick(rightTitle: Int?, clickListener:View.OnClickListener, rightTitleColor: Int?) {
        rightTitle ?: return
        findViewById<TextView>(R.id.right_title)?.setText(rightTitle)
        findViewById<TextView>(R.id.right_title)?.setTextColor(resources.getColor(rightTitleColor?:R.color.color_33))
        findViewById<TextView>(R.id.right_title)?.visibility = View.VISIBLE
        findViewById<TextView>(R.id.right_title)?.setOnClickListener(clickListener)
    }

    override fun onResume() {
        super.onResume()
        MobclickAgent.onResume(this)
    }

    override fun onPause() {
        super.onPause()
        mProgressLoadingDialog?.destroy()
        MobclickAgent.onPause(this)
    }


}